package summer.student.Filter;

import com.auth0.jwt.interfaces.Claim;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import summer.student.Dao.AdminDao;
import summer.student.Domain.Admin;
import summer.student.Utils.JwtUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @program: student
 * @description:
 * @author: hlt
 * @create: 2023-07-23 16:46
 **/
@Slf4j
@WebFilter(filterName = "adminFilter", urlPatterns = "/admins/*")   // 所有前往adminController的请求都将被拦截
public class adminFilter implements Filter {

    @Autowired
    private AdminDao adminDao;

    private static final String SECRET_KEY = "my_secret";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;

        response.setCharacterEncoding("UTF-8");
        //获取 header里的token
        final String token = request.getHeader("Authorization");

        // 设置过滤器里的例外
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        }
        else {
            //验证token
            Map<String, Claim> stringClaimMap = JwtUtil.verifyToken(token);
            if (stringClaimMap != null) {
                // 验证通过则继续处理请求
                chain.doFilter(request, response);
            }else{
                sendError(response, HttpServletResponse.SC_UNAUTHORIZED, "Token已过期或无效");
            }
        }
    }

    @Override
    public void destroy() {
    }

    private void sendError(HttpServletResponse response, int status, String message) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(status);
        PrintWriter writer = response.getWriter();
        writer.write("{\"error\": \"" + message + "\"}");
        writer.flush();
    }
}
